package com.smartown.learning.androiddevelopart.chapters.chapter2.section3.part1;

import android.widget.TextView;

import com.smartown.learning.androiddevelopart.R;
import com.smartown.library.ui.base.BaseFragment;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Author:Smartown
 * Date:2016/11/28 22:50
 * Description:2.3.1 Serializable接口
 */
public class SerializableFragment extends BaseFragment {

    private TextView originTextView;
    private TextView resultTextView;

    @Override
    protected void init() {
        findViews(R.layout.fragment_2_3_1);
    }

    @Override
    protected void findViews() {
        originTextView = (TextView) findViewById(R.id.serializable_origin);
        resultTextView = (TextView) findViewById(R.id.serializable_result);
    }

    @Override
    protected void initViews() {
        final User user = new User(1, "tiger", true);
        originTextView.setText(user.toString());
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(getActivity().getExternalCacheDir().getPath() + "/user.txt");
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(user);
            outputStream.close();

            FileInputStream fileInputStream = new FileInputStream(getActivity().getExternalCacheDir().getPath() + "/user.txt");
            ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
            User newUser = (User) inputStream.readObject();
            resultTextView.setText(newUser.toString());
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void registerViews() {

    }
}
